package com.quectel.core.module.workorder.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.lock.annotation.Lock;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.constants.RedisLockConstants;
import com.quectel.core.module.workorder.dao.WorkOrderLogDao;
import com.quectel.core.module.workorder.dto.WorkOrderLogDto;
import com.quectel.core.module.workorder.entity.WorkOrderLogEntity;
import com.quectel.core.module.workorder.service.WorkOrderLogService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.redis.RedisUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2021-10-19 13:06:44
 */
@DubboService
public class WorkOrderLogServiceImpl implements WorkOrderLogService {

    private static final Logger LOGGER = LoggerFactory.getLogger(WorkOrderLogServiceImpl.class);
    private static final String WORK_ORDER_LOG_LOCK = RedisCacheConstants.PROJECT_NAME + "WORK_ORDER_LOG_LOCK";

    @Autowired
    private WorkOrderLogDao workOrderLogDao;


    @Override
    public List<WorkOrderLogDto> selectByWorkOrderId(Long workOrderId) {
        List<WorkOrderLogEntity> entityList = workOrderLogDao.selectList(new LambdaQueryWrapper<WorkOrderLogEntity>()
                .eq(WorkOrderLogEntity::getWorkOrderId, workOrderId)
        );
        return CopyUtils.copyList(entityList, WorkOrderLogDto.class);
    }

    @Override
    public List<WorkOrderLogDto> queryList(Map<String, Object> params) {
        List<WorkOrderLogEntity> list = workOrderLogDao.queryList(params);
        return CopyUtils.copyList(list, WorkOrderLogDto.class);
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return workOrderLogDao.queryTotal(params);
    }

    @Override
    @Lock(
            lockExpresses = {
                    RedisLockConstants.WORK_ORDER_LOG_SEQ_INC_LOCK + "#{#dto.workOrderId}"
            }
    )
    public Long save(WorkOrderLogDto dto) {
        WorkOrderLogEntity entity = CopyUtils.copyObj(dto, WorkOrderLogEntity.class);
        entity.setId(Snowflake.nextId());


        java.util.concurrent.locks.Lock spinLock = RedisUtils.getSpinLock(WORK_ORDER_LOG_LOCK + dto.getWorkOrderId());
        spinLock.lock();
        try {

            List<WorkOrderLogDto> dbLogs = selectByWorkOrderId(dto.getWorkOrderId());
            int maxSeq = dbLogs == null ?
                    SystemConstants.ZERO.intValue() :
                    dbLogs.stream().map(WorkOrderLogDto::getSeq).filter(Objects::nonNull).max(Integer::compareTo).orElse(SystemConstants.ZERO.intValue());
            entity.setSeq(maxSeq + 1);
            workOrderLogDao.insert(entity);
        } finally {
            spinLock.unlock();
        }
        return entity.getId();
    }

    @Override
    public void updateById(WorkOrderLogDto dto) {
        WorkOrderLogEntity entity = CopyUtils.copyObj(dto, WorkOrderLogEntity.class);
        workOrderLogDao.updateById(entity);
    }

    @Override
    public WorkOrderLogDto selectById(Long id) {
        WorkOrderLogEntity entity = workOrderLogDao.selectById(id);
        return CopyUtils.copyObj(entity, WorkOrderLogDto.class);
    }

    @Override
    public void deleteById(Long id) {
        workOrderLogDao.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
